<template>
    <view class="w-[100%] relative">
        <z-paging :empty-view-error-text="`对不起,页面走丢了\n请刷新试试`" :empty-view-text="`暂无设备去添加宠物吧`" empty-view-img="/static/images/img/shebei.png" empty-view-center ref="paging" v-model="deviceList"
            @query="queryList" :fixed="true" width="100%" height="100%" >
            <!-- <template>
                <up-navbar title="" :autoBack="false" placeholder bgColor="rgba(255,255,255,0)">
                    <template #left>
                        <text class="text-[34rpx] text-[#000] font-[500]">我的设备</text>
                    </template>
                </up-navbar>
            </template> -->
            <view class="dasdds">
                <view v-for="(device, index) in deviceList" :key="device.index" 
                    class="w-[332rpx] h-[526rpx] bg-[#FFFFFF] rounded-[24rpx] pt-[34rpx] relative">
                    <view class="ml-[208rpx]">
                        <up-switch v-model="device.status" @change="(e) => changeStatus(e, device)" size="20"></up-switch>
                    </view>
                    <view class="flex justify-center mt-[24rpx]">
                        <image src="@/static/images/img/sb.png" class="w-[150rpx] h-[148rpx]"></image>
                    </view>

                    <view class="text-[22rpx] flex items-center justify-center text-[#666666] mt-[24rpx]">
                        <battery class="w-[126rpx] h-[44rpx]" :size="6" :value="device.energy || 0"></battery>
                        <text class="text-[24rpx] font-[500] ml-[16rpx] text-[#000000] font-[PingFang SC]">
                            {{ device.energy || 0 }}%
                        </text>
                    </view>
                    <view  @click.stop="confirmDelete(device)" class="flex justify-center mt-[42rpx]">
                        <image src="@/static/images/img/scsb.png" class="w-[220rpx] h-[60rpx]"></image>
                    </view>
                </view>
            </view>
            <template #bottom>
                <!-- 添加按钮 -->
                <view @click="push('/pages_cw/addpets/addpets')"
                    class=" text-[#000000] flex justify-center mb-[32rpx]"
                   >
                    <image src="@/static/images/img/tjsb.png" class="w-[538rpx] h-[108rpx]"></image>
                </view>
               
            </template>

        </z-paging>
    </view>
</template>

<script setup>
import { ref } from 'vue';
import { getDeviceList, closeDevice, delDevice } from '@/api/pet';
import { onShow } from '@dcloudio/uni-app';
import useUserStore from '@/store/modules/user';

const userStore = useUserStore();
const deviceList = ref([]);
const paging = ref(null);

// 获取设备列表数据
const queryList = async (pageNum, pageSize) => {
    try {
        const params = {
            pageNum: pageNum,
            pageSize: pageSize,
            uid: userStore.userId
        };
        const { rows } = await getDeviceList(params);
        // 处理设备状态，确保每个设备有status属性，并转换为布尔值
        const processedRows = rows.map(device => ({
            ...device,
            status: device.status == 1 // 转换为布尔值用于switch组件
        }));
        paging.value.complete(processedRows);
    } catch (e) {
        console.log('获取设备列表失败:', e);
        paging.value.complete(false);
    }
};

// 切换设备状态
const changeStatus = async (e, device) => {
    console.log('设备状态变更:', e, '设备ID:', device.id);
    // 保存原始状态值，用于失败时恢复
    const originalStatus = device.status;
    try {
        const data = {
            clientId: device.clientId,
            status: e ? 1 : 0 // 转换布尔值为数字状态
        };
        await closeDevice(data);
        uni.showToast({
            title: e ? '设备已开启' : '设备已关闭',
            icon: 'success'
        });
    } catch (error) {
        console.error('更新设备状态失败:', error);
        // 恢复为原始状态值
        device.status = originalStatus;
        uni.showToast({
            title: '操作失败，请重试',
            icon: 'none'
        });
    }
};

// 确认删除设备
const confirmDelete = (device) => {
    uni.showModal({
        title: '提示',
        content: '确定要删除此设备吗？',
        success: async (res) => {
            if (res.confirm) {
                await deleteDevice(device);
            }
        }
    });
};

// 删除设备
const deleteDevice = async (device) => {
    try {
        const data = {
            id: device.id
        };
        await delDevice(data);
        uni.showToast({
            title: '设备已删除',
            icon: 'success'
        });
        // 刷新设备列表
        if (paging.value) {
            paging.value.reload();
        }
    } catch (error) {
        console.error('删除设备失败:', error);
        uni.showToast({
            title: '删除失败，请重试',
            icon: 'none'
        });
    }
};

// 刷新页面数据
onShow(() => {
    // 每次页面显示时刷新数据
    if (paging.value) {
        paging.value.reload();
    }
});
</script>

<style scoped lang="scss">
.dasdds {
    padding-left: 40rpx;
    padding-right: 40rpx;
    width: 100%;
    margin-top: 42rpx;
    display: grid;
    grid-template-columns: repeat(2, 1fr);
    gap: 28rpx; // 间隙
}
</style>